'''
Copyright (C) <2011> by Kevin Klein

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import sys
try:
    import json
except:
    import simplejson as json
try:
    from .rpc import Handler
except ValueError:
    from rpc import Handler

class JSONHandler(Handler):

    '''
    this is version 1.1
    '''
    
    def __init__(self, loader, name='', debug=False):
        Handler.__init__(self, name, debug)
        self.loader = loader
    
    def register_function(self, func, name=''):
        if not name:
            name = func.__name__
        super(JSONHandler, self).register_function(func, name)
        router = self.loader.get_component('server.WSGI_Server').get_router()
        
        @router.route('/rpc/doc/' + name)
        def doc(header, request, response):
            pass

    def __describe(self):
        description = {
            'name'    : '',
            'id'      : '',
            'summary' : '',
            'help'    : '',
            'address' : '/rpc',
            'procs' : []
        }
        for name, func in self.funcs.items():
            if name.startswith('system.'):
                continue
            method_desc = {
                'name'    : name,
                'summary' : func.func_doc if hasattr(func, 'func_doc') else '',
                'help'    : 'http://localhost:8000/rpc/doc/'+name,
                'params'  : [],
                'return' : {
                    'type' : 'any'
                 }, 
            }
            if hasattr(func, 'func_code'):
                for var in func.func_code.co_varnames[:func.func_code.co_argcount]:
                    var_desc = { 'name' : var, 'type' : 'any' }
                    method_desc['params'].append(var_desc)
            
            description['procs'].append(method_desc)
        return description

    def register_introspection(self):
        self.register_function(self.__describe, 'system.describe')

    def generate_response(self, args):
        #example: { 
        #    'version': '1.1', 
        #    'result': 'done', 
        #    'error': null, 
        #    'id': '194521489'
        #}
        return json.dumps({'version' : '1.1', 'result': args, 'error': None, 'id': 1})
        
    def parse_request(self, data):
        #example: { 
        #    'version': '1.1', 
        #    'method': 'confirmFruitPurchase', 
        #    'id': '194521489', 
        #    'params': 
        #    [ 
        #        [ 'apple', 'orange', 'pear' ], 
        #        1.123 
        #    ]
        #}
        data = json.loads(data)
        return data['method'], data['params']
    
    def render_error(self, name, msg):
        return json.dumps({'id' : 1, 'result': None, 'error': {'name': name, 'message': msg}})
        
    def validate(self, request):
        data = json.loads(request)
            
        try:
            method = data['version']
            if method != '1.1':
                return (False, 'invalid request', 'id is not "1.1", probably it is a 1.0 request')
        except KeyError:
            err = sys.exc_info()[1]
            return (False, 'invalid request', 'version is not given')
            
        try:
            params = data['params']
        except KeyError:
            err = sys.exc_info()[1]
            return (False, 'invalid request', 'params are not given')
            
        try:
            method = data['method']
        except KeyError:
            err = sys.exc_info()[1]
            return (False, 'invalid request', 'method name is not given')
            
        if method not in self.funcs.keys():
            return (False, 'method not found', 'method {0} not found'.format(method))
        return (True, '', '')
        
